from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5 import QtGui
import pyqtgraph as pg
import numpy as np
import sys

def rand(n):
    data = np.random.random(n)
    data[int(n*0.1):int(n*0.13)] += .5
    data[int(n*0.18)] += 2
    data[int(n*0.1):int(n*0.13)] *= 5
    data[int(n*0.18)] *= 20
    data *= 1e-12
    return data, np.arange(n, n+len(data)) / float(n)


def ydot(t, y):
    z = np.zeros(2)
    z[0] = y[1]**2 - 2 * y[0]
    z[1] = y[0] - y[1] - t * (y[1] ** 2)
    return z

def eulerstep(t, y, h):
    result = y + h * ydot(t, y)
    return result

def euler2(inter, y0, n):
    t = np.zeros(n+1)
    t[0] = inter[0]

    y = np.zeros((n+1, 2))
    y[0, :] = y0
    h = (inter[1] - inter[0])/n

    for i in range(0, n):
        t[i+1] = t[i] + h
        y[i+1, :] = eulerstep(t[i], y[i, :], h)
    
    return t, y


class QDialogTest(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(QDialogTest, self).__init__(parent)

        self.setWindowTitle("QDialogTest例子")

        self.resize(300, 300)

        self.btn_dialog = QtWidgets.QPushButton(self)
        self.btn_dialog.setText("弹出对话框")
        self.btn_dialog.clicked.connect(self.btn_dialog_clicked)

        self.sketch_pad = pg.PlotWidget(name="plot1")
        self.sketch_pad.setBackground(QtGui.QColor(255, 255, 255))
        self.sketch_pad.showGrid(x=True, y=True)

        self.p1 = self.sketch_pad.plot()
        self.p1.setPen((255,0,0))

        self.p2 = self.sketch_pad.plot()
        self.p2.setPen((0,255,0))

        _v_box = QtWidgets.QVBoxLayout()
        _v_box.addWidget(self.btn_dialog)
        _v_box.addWidget(self.sketch_pad)
        self.setLayout(_v_box)

        self.start_data_generator()

    def update_data(self):
        yd, xd = rand(10000)
        self.p1.setData(y=yd, x=xd)

    def start_data_generator(self):
        t, y = euler2([0, 1], [0, 1], 10)
        self.p1.setData(x=t, y=y[:, 0])
        self.p2.setData(x=t, y=y[:, 1])

    def btn_dialog_clicked(self):
        dialog = QtWidgets.QDialog()
        btn = QtWidgets.QPushButton("ok", dialog)
        btn.move(50, 50)

        dialog.setWindowTitle("Dialog")
        dialog.setWindowModality(QtCore.Qt.ApplicationModal)
        dialog.exec_()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    win = QDialogTest()
    win.show()
    sys.exit(app.exec_())